package com.itxing.service;

import com.alibaba.fastjson.JSON;
import com.itxing.pojo.Content;
import com.itxing.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xing
 * @create 2020/7/19-studyes
 * 业务层代码
 */
@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //将解析的数据放入ES中
    public Boolean parseContext(String keyWorld) throws Exception {
        List<Content> contents =  new HtmlParseUtil().parseJD(keyWorld);
        //数据将解析的数据放入ES中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        for(int i=0;i<contents.size();i++){
            bulkRequest.add(new IndexRequest("jd_goods")
            .source(JSON.toJSONString(contents.get(i)), XContentType.JSON));

        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }
    
    //获取数据实现搜索功能
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1)pageNo=1;
        
        //条件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for(SearchHit documentFields:response.getHits().getHits()){
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }

    //3.搜索高亮功能
    public List<Map<String,Object>> searchPageHighLight(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=1)pageNo=1;

        //条件搜索
        SearchRequest request = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQuery = QueryBuilders.termQuery("title", keyword);
        sourceBuilder.query(termQuery);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮设置
        HighlightBuilder highlighterBuilder = new HighlightBuilder();
        highlighterBuilder.field("title");
        highlighterBuilder.requireFieldMatch(false);
        highlighterBuilder.preTags("<span style='color:red'>");
        highlighterBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlighterBuilder);

        //执行搜索
        request.source(sourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String,Object>> list = new ArrayList<>();
        for(SearchHit dochit:response.getHits().getHits()){
            //解析高亮字段
            Map<String, HighlightField> highlightFields = dochit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = dochit.getSourceAsMap();
            if(title!=null){
                Text[] fragments = title.fragments();
                String n_title = "";
                for(Text text:fragments){
                    n_title +=text;
                }
                sourceAsMap.put("title",n_title);
            }

            list.add(sourceAsMap);
        }
        return list;
    }


}
